import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:syn_4s/core/constants/event_code.dart';
import 'package:syn_4s/core/extension/int_extension.dart';
import 'package:syn_4s/core/utils/event_bus.dart';
import 'package:syn_4s/core/utils/sp_utils.dart';
import 'package:syn_4s/core/viewmodel/main_view_model.dart';
import 'package:syn_4s/ui/widgets/custom_ui.dart';
import 'package:syn_4s/ui/widgets/main_gas_monitoring.dart';
import 'package:syn_4s/ui/widgets/main_info.dart';
import 'package:syn_4s/ui/widgets/main_map.dart';
import 'package:syn_4s/ui/widgets/main_safety_training.dart';
import 'package:syn_4s/ui/widgets/main_tracking_system.dart';
import 'package:syn_4s/ui/widgets/refresh_content.dart';

import '../../../core/constants/sp_key.dart';
import '../../../core/constants/tag_code.dart';
import '../../../core/model/user_tag_model.dart';
import '../../shared/app_theme.dart';
import '../../widgets/main_360_plant.dart';
import '../../widgets/main_alert.dart';
import '../../widgets/main_permit_to_work.dart';
import '../../widgets/main_smart_lock.dart';
import '../../widgets/main_smart_watch.dart';
import '../../widgets/main_unsafe_act.dart';

class MainContent extends StatefulWidget {
  const MainContent({super.key});

  @override
  State<MainContent> createState() => _MainContentState();
}

class _MainContentState extends State<MainContent> {
  final ScrollController _controller = ScrollController();
  final GlobalKey _keyPermitToWork = GlobalKey();
  final GlobalKey _keySafetyTraining = GlobalKey();
  final GlobalKey _keyGasMonitoring = GlobalKey();
  final GlobalKey _keySmartWatch = GlobalKey();
  final GlobalKey _keySmartLock = GlobalKey();
  final GlobalKey _keyTrackingSystem = GlobalKey();
  final GlobalKey _key360Plant = GlobalKey();
  final GlobalKey _keyAlert = GlobalKey();
  final GlobalKey _keyUnsafeAct = GlobalKey();
  final MainViewModel viewModel = Get.find<MainViewModel>();

  @override
  void initState() {
    super.initState();
    listenMap((value) {
      if (value[eventType] == eventScroll) {
        jump(value[eventValue]);
      }
    });

    _controller.addListener(() {
      changeScrollStatus(
          _controller, _keySafetyTraining, viewModel.isSafetyScrollable);
      changeScrollStatus(
          _controller, _keyGasMonitoring, viewModel.isGasScrollable);
      changeScrollStatus(
          _controller, _keySmartWatch, viewModel.isWatchScrollable);
      changeScrollStatus(
          _controller, _keySmartLock, viewModel.isLockScrollable);
      changeScrollStatus(
          _controller, _key360Plant, viewModel.is360PlantScrollable);
      changeScrollStatus(_controller, _keyAlert, viewModel.isAlertScrollable);
      changeScrollStatus(
          _controller, _keyUnsafeAct, viewModel.isUnsafeScrollable);
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void jump(int? value) {
    if (value == null) return;
    double dy = 0;
    if (value == eventPermitToWork) {
      dy = getDy(_keyPermitToWork);
    } else if (value == eventSafetyTraining) {
      dy = getDy(_keySafetyTraining);
    } else if (value == eventGasMonitoring) {
      dy = getDy(_keyGasMonitoring);
    } else if (value == eventSmartWatch) {
      dy = getDy(_keySmartWatch);
    } else if (value == eventSmartLock) {
      dy = getDy(_keySmartLock);
    } else if (value == eventTrackingSystem) {
      dy = getDy(_keyTrackingSystem);
    } else if (value == event360) {
      dy = getDy(_key360Plant);
    } else if (value == eventAlert) {
      dy = getDy(_keyAlert);
    } else if (value == eventUnsafeAct) {
      dy = getDy(_keyUnsafeAct);
    }
    _controller.animateTo(_controller.offset + dy - 84.px,
        duration: const Duration(seconds: 1), curve: Curves.ease);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12.px),
      height: double.infinity,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
            colors: [AppTheme.bgStartColor, AppTheme.bgEndColor]),
      ),
      child: FutureBuilder<dynamic>(
        future: SPUtils.get(keyTag),
        builder: (ctx, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const SingleChildScrollView(
              child: Center(
                child: CircularProgressIndicator(),
              ),
            );
          } else if (snapshot.hasError) {
            return SingleChildScrollView(
              child: Container(),
            );
          } else {
            if (snapshot.data == null || snapshot.data.isEmpty) {
              return Container();
            }
            List<UserTagModel> tags = (jsonDecode(snapshot.data ?? "") as List)
                .map((e) => UserTagModel.fromJson(e))
                .where(
                    (e) => e.code != codeStatus && e.code != codeSurveillance)
                .toList();
            return RefreshContent(
                onRefresh: (refreshController) {
                  viewModel.getDash(controller: refreshController);
                },
                enableLoadMore: false,
                child: CustomScrollView(
                    controller: _controller,
                    slivers: List.generate(tags.length + 1, (index) {
                      if (index == 0) {
                        return SliverToBoxAdapter(
                          child: buildInfo(),
                        );
                      } else {
                        String? name = tags[index - 1].name;
                        switch (tags[index - 1].code) {
                          case codeRealLocation:
                            return SliverToBoxAdapter(child: buildMap(context));
                          case codePermitToWork:
                            return SliverToBoxAdapter(
                                child: buildPermitToWork(context, name));
                          case codeSafetyTraining:
                            return SliverToBoxAdapter(
                                child: buildSafetyTraining(context, name));
                          case codeGas:
                            return SliverToBoxAdapter(
                                child: buildGasMonitoring(context, name));
                          case codeWatch:
                            return SliverToBoxAdapter(
                                child: buildSmartWatch(context, name));
                          case codeLock:
                            return SliverToBoxAdapter(
                                child: buildSmartLock(context, name));
                          case codeTracking:
                            return SliverToBoxAdapter(
                                child: buildTrackingSystem(context, name));
                          case code360:
                            return SliverToBoxAdapter(
                                child: build360Plant(context, name));
                          case codeAlert:
                            return SliverToBoxAdapter(
                                child: buildAlert(context, name));
                          case codeUnSafeAct:
                            return SliverToBoxAdapter(
                                child: buildUnsafeAct(context, name));
                        }
                        return SliverToBoxAdapter(child: Container());
                      }
                    })));
          }
        },
      ),
    );
  }

  Widget buildUnsafeAct(BuildContext context, String? title) {
    return MainUnsafeAct(
      viewModel: viewModel,
      title: title,
      scrollKey: _keyUnsafeAct,
    );
  }

  Widget buildAlert(BuildContext context, String? title) {
    return MainAlert(
      viewModel: viewModel,
      title: title,
      scrollKey: _keyAlert,
    );
  }

  Widget build360Plant(BuildContext context, String? title) {
    return Main360Plant(
      viewModel: viewModel,
      title: title,
      scrollKey: _key360Plant,
    );
  }

  Widget buildTrackingSystem(BuildContext context, String? title) {
    return MainTrackingSystem(
        title: title, scrollKey: _keyTrackingSystem, viewModel: viewModel);
  }

  Widget buildSmartLock(BuildContext context, String? title) {
    return MainSmartLock(
      viewModel: viewModel,
      title: title,
      scrollKey: _keySmartLock,
    );
  }

  Widget buildSmartWatch(BuildContext context, String? title) {
    return MainSmartWatch(
      viewModel: viewModel,
      title: title,
      scrollKey: _keySmartWatch,
    );
  }

  Widget buildGasMonitoring(BuildContext context, String? title) {
    return MainGasMonitoring(
      viewModel: viewModel,
      title: title,
      scrollKey: _keyGasMonitoring,
    );
  }

  Widget buildSafetyTraining(BuildContext context, String? title) {
    return MainSafetyTraining(
      viewModel: viewModel,
      title: title,
      scrollKey: _keySafetyTraining,
    );
  }

  Widget buildPermitToWork(BuildContext context, String? title) {
    return MainPermitToWork(
      viewModel: viewModel,
      title: title,
      scrollKey: _keyPermitToWork,
    );
  }

  Widget buildMap(BuildContext context) {
    return MainMap(viewModel: viewModel);
  }

  /// 顶部信息
  Widget buildInfo() {
    return MainInfo(
      viewModel: viewModel,
    );
  }
}
